package dobest.ray.com.jiongjiong.views;

import android.app.Dialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TextView;

import java.util.Calendar;

import dobest.ray.com.jiongjiong.R;

/**
 * Created by Ray on 2016/4/27.
 * https://github.com/ray0807
 */
public class DatePickerDialog {
    private Context c;
    private Dialog dialog;
    private DatePicker datePicker;

    private TextView tv_cancle;
    private TextView tv_confirm;
    private DateCallback callback;

    public DatePickerDialog(Context c) {
        this.c = c;
        init();
    }

    private void init() {
        dialog = new Dialog(c, R.style.CustomDialog);
        LayoutInflater inflater = LayoutInflater.from(c);
        final View v1 = inflater.inflate(R.layout.dialog_date_picker, null);
        dialog.setContentView(v1);// 设置使用View
        datePicker = (DatePicker) v1.findViewById(R.id.date_picker);
        //设置日期简略显示 否则详细显示 包括:星期周
        datePicker.setCalendarViewShown(false);
        //初始化当前日期
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        datePicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH), null);

        tv_confirm = (TextView) v1.findViewById(R.id.tv_confirm);
        tv_cancle = (TextView) v1.findViewById(R.id.tv_cancle);
        tv_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });

        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (callback != null) {
                    callback.backDate(datePicker.getYear() + "-" + (datePicker.getMonth() + 1) + "-" + datePicker.getDayOfMonth());
                }
                dismiss();
            }
        });
    }

    public void show() {
        if (!dialog.isShowing())
            dialog.show();
    }

    public void dismiss() {
        if (dialog.isShowing())
            dialog.dismiss();
    }

    public void setComfirmListener(DateCallback listener) {
        this.callback = listener;
    }

    public interface DateCallback {
        void backDate(String date);
    }
}
